package com.jl.magic.montage.tessera;

import com.jl.magic.extract.ColorExtract;
import com.jl.magic.montage.config.SquareInlayConfig;
import com.jl.magic.montage.model.Inlay;
import com.jl.magic.utils.ImageUtils;
import org.imgscalr.Scalr;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author jiangli
 * @create 2020/7/14 3:57 下午
 */
public class SquareInlayHandler extends AbstractInlayHandler {

    @Override
    public List<Inlay> handleInlay() {

        SquareInlayConfig config = (SquareInlayConfig) inlayConfig;
        int side = config.getSide();

        AtomicInteger no = new AtomicInteger(1);

        List<Inlay> inlayList = Collections.synchronizedList(new ArrayList<>());
        files.parallelStream().forEach(input -> {
            try {
                long start = System.currentTimeMillis();
                BufferedImage bfi = ImageIO.read(input);
                long end1 = System.currentTimeMillis();

                //裁剪图片
                bfi = ImageUtils.tailor(bfi);

                long end2 = System.currentTimeMillis();

                int width = bfi.getWidth();
                float rate = side * 1.0f / width;

                //缩放图片
                bfi = Scalr.resize(bfi, side);
                //bfi = ImageUtils.scale(bfi, rate, ScaleEnum.SMOOTH);

                long end3 = System.currentTimeMillis();

                //压缩图片
                if (compressed) {
                    //bfi = Thumbnails.of(bfi).scale(0.75f).asBufferedImage();
                }

                long end4 = System.currentTimeMillis();

                //获取主色调
                int[] rgb = ColorExtract.getThemeColor(bfi, true);

                long end5 = System.currentTimeMillis();
                System.out.println("镶嵌图片处理：图片读取耗时：" + (end1 - start) + "ms，图片裁剪耗时：" + (end2 - end1) +
                        "ms，图片缩放耗时：" + (end3 - end2) + "ms，图片压缩耗时：" + (end4 - end3) + "ms，图片获取主色调耗时：" +
                        (end5 - end4) + "ms");

                Inlay inlay = new Inlay();
                inlay.setNo(no.getAndAdd(1));
                inlay.setBufferedImage(bfi);
                inlay.setRgb(rgb);
                inlayList.add(inlay);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        //clear by gc
        files = null;
        return inlayList;
    }

}
